package com.duan.blog.config;

import com.duan.blog.common.CustomException;
import com.duan.blog.constants.CodeEnum;
import com.duan.blog.model.vo.NamePasswordVo;
import com.duan.blog.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class CustomRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;

    /**
     * 获取授权信息
     * @param principals    PrincipalCollection
     * @return              AuthorizationInfo
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("-----权限信息认证-----");
        return null;
    }

    /**
     * 获取身份验证信息
     * 通过Realm 获取应用程序中的用户、角色以及权限信息
     *
     * @param authenticationToken       用户身份信息token
     * @return                          返回封装了用户信息的 AuthenticationInfo
     * @throws AuthenticationException  异常
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("-----身份信息认证-----");
        String token = (String)authenticationToken.getCredentials();
        String userName = JWTUtil.getUsername(token);
        if(userName == null){
            throw new CustomException(CodeEnum.TOKEN_ERROR);
        }
        NamePasswordVo namePasswordVo = userService.selectNameAndPasswordByName(userName);
        if(namePasswordVo == null){
            throw new CustomException(CodeEnum.USER_INVALID_ERROR);
        }
        if(!JWTUtil.verify(token, userName)){
            throw new CustomException(CodeEnum.NAME_PASSWORD_ERROR);
        }

        return new SimpleAuthenticationInfo(token, token, getName());
    }
}
